#   This file is part of Metriflot.
#
#    Metriflot is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Metriflot is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Metriflot.  If not, see <http://www.gnu.org/licenses/>.
#
#    Copyright 2011 David Irvine
# 

import urllib2
import json
import os
import sys, socket
import time
import psutil
import subprocess


def iostat(disk):
	op=subprocess.check_output(["iostat","-d",disk])
	lines=op.splitlines()
	data=lines[2].split()
	return [["KBPerTransfer"+disk,data[0]],
			["TransfersOpsSec"+disk,data[1]],
			["TransfersMBSec"+disk,data[2]]
		  ] 








data=[]
disks=['disk0']
for disk in disks:
	stats=iostat(disk)
	for s in stats:
		data.append(s)

mem=psutil.phymem_usage()
data.append(["PhysMemTotal",mem[0]])
data.append(["PhysMemUsed",mem[1]])
data.append(["PhysMemFree",mem[2]])
data.append(["PhysMemPerc",mem[3]])

usage=psutil.disk_usage("/")
data.append(["Disk0Total",usage[0]])
data.append(["Disk0Used",usage[1]])
data.append(["Disk0Free",usage[2]])
data.append(["Disk0Perc",usage[3]])

i=0
for cpu in psutil.cpu_percent(interval=1, percpu=True):
	data.append(["CPU"+str(i),cpu])
	i+=1

send=[]
ts=time.time()
hostname = socket.gethostname()
for item in data:
	send.append({
		'system':hostname,
		'ts':ts,  
		'series':item[0],
		'value':item[1],
		})



# define a Python data dictionary
s = os.statvfs('/')
space= s.f_bsize * s.f_bavail/1024/1024/1024
data_json=json.dumps(send,sort_keys=True, indent=4)
print data_json

host = "http://localhost/metriflot/metric/upload"
req = urllib2.Request(host, data_json, {'content-type': 'application/json'})
response_stream = urllib2.urlopen(req)
response = response_stream.read()

